package cn.seamus.marksman.processor.impl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.cookie.Cookie;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import cn.seamus.marksman.common.Constants;
import cn.seamus.marksman.common.MarksmanException;
import cn.seamus.marksman.common.PageNavigator;

public class LoginProcessor extends AbstractProcessor {
    private static Log logger = LogFactory.getLog(LoginProcessor.class);

    private String loginUrl;
    private String loginUsername;
    private String loginPassword;

    @Override
    protected Map<String, Object> prepareNext(Map<String, Object> params) throws MarksmanException {
        return null;
    }

    @Override
    protected ProcessResult read(Map<String, Object> requestParams) throws MarksmanException {
        logger.info("Login begin. url=" + this.loginUrl + ", username=" + this.loginUsername);

        URL loginURL = null;
        try {
            loginURL = new URL(loginUrl);
        } catch (MalformedURLException e) {
            throw new MarksmanException("Cannot create loginPageURL: loginUrl=" + loginUrl, e);
        }

        // send login request.
        Map<String, Object> reqParams = new HashMap<String, Object>();
        reqParams.put(Constants.REQ_PARAM_NAME_FORM_TYPE, "customer_login");
        reqParams.put(Constants.REQ_PARAM_NAME_UTF8, "✓");
        reqParams.put(Constants.REQ_PARAM_NAME_LOGIN_USERNAME, loginUsername);
        reqParams.put(Constants.REQ_PARAM_NAME_LOGIN_PASSWORD, loginPassword);
        CloseableHttpResponse response = executePost(loginURL, reqParams);

        ProcessResult result = new ProcessResult();
        Map<String, Object> resMap = new HashMap<String, Object>();
        result.setParams(resMap);
        try {

            boolean isSuccess = false;
            for (Header head : response.getAllHeaders()) {
                if (head.getName().equalsIgnoreCase("Status")) {
                    isSuccess = head.getValue().equalsIgnoreCase("200 OK");
                }
                resMap.put(head.getName(), head.getValue());
            }

            String body = EntityUtils.toString(response.getEntity());

            Document doc = Jsoup.parse(body);

            if (isSuccess) {
                result.setNavigator(PageNavigator.OPEN_GOODS);
            }

        } catch (IOException e) {
            throw new MarksmanException("Cannot parse  content", e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
            }
        }

        logger.info("Login end.");
        return result;
    }

    /**
     * @return the loginUrl
     */
    public String getLoginUrl() {
        return loginUrl;
    }

    /**
     * @param loginUrl
     *            the loginUrl to set
     */
    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    /**
     * @return the loginUsername
     */
    public String getLoginUsername() {
        return loginUsername;
    }

    /**
     * @param loginUsername
     *            the loginUsername to set
     */
    public void setLoginUsername(String loginUsername) {
        this.loginUsername = loginUsername;
    }

    /**
     * @return the loginPassword
     */
    public String getLoginPassword() {
        return loginPassword;
    }

    /**
     * @param loginPassword
     *            the loginPassword to set
     */
    public void setLoginPassword(String loginPassword) {
        this.loginPassword = loginPassword;
    }

}
